import React from 'react';
import PropTypes from 'prop-types';
import {Spin, Card, Button, Row, Col, Table, Divider} from 'antd';
import {TABLE, DATETIME_FORMAT} from '../constants';
import DescriptionList from 'ant-design-pro/lib/DescriptionList';
import routes from './routes';
import {abandonData, submitData, getDetail} from './api';
import {injectIntl} from './intl';
import {currency, saleOrderPriceTerms, paymentType, saleOrderTransportType, packingWay, saleOrderType, saleOrderResultJudgeResult} from '../Enum';
import {conventEnumValueToString, formatDateTime, formatAmount, formatPercent, exportDownload} from '../utils';
import {hasPermissions} from './utils';
import {PERMISSION, formatExportPdfUrl} from './constants';
import WrappedPopconfirm from '../common/WrappedPopconfirm';
import styles from './style.css';
import Ellipsis from 'ant-design-pro/lib/Ellipsis';
const {Description} = DescriptionList;
export class DetailPanel extends React.PureComponent {
    state = {
        loading: false,
        data: {},
    }
    componentDidMount() {
        this.getDetailInfo();
    }
    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data,
                        details: res.data.details,
                        saleConfirmationResults: res.data.saleConfirmationResults,
                    });
                else
                    this.setState(({
                        loading: false
                    }));
            });
    }
    handleUpdateClick = () => {
        this.props.history.push(routes.update.format(this.props.id));
    }
    handleApproveClick = () => {
        this.props.history.push(routes.approve.format(this.props.id));
    }
    onClickAbandonBtn = () => {
        this.setState({loading: true});
        abandonData(this.state.data.id, {rowVersion: this.state.data.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onClickSubmitBtn = () => {
        this.setState({loading: true});
        submitData(this.state.data.id, {rowVersion: this.state.data.rowVersion})
            .then(res => {
                this.setState({loading: false});
                if(res.ok)
                    this.props.successReturn();
            });
    }
    onPrint = () => {
        this.setState({loading: true});
        this.props.printData(this.props.id)
            .then(res => {
                this.setState({loading: false});
                exportDownload(res);
            });
    }
    onPrintPdf = e => {
        e.stopPropagation();
        window.open(formatExportPdfUrl(e.currentTarget.dataset.id, e.currentTarget.dataset.code));
    }
    render() {
        const {formatMessage} = this.props.intl;
        const {data, details, saleConfirmationResults} = this.state;
        let totalAmount = 0;
        let totalQuantity = 0;
        if(details)
            details.forEach(v => {
                totalAmount += v.totalPrice;
                totalQuantity += v.quantity;
            });
        const operations = [];

        const columns = [{
            title: formatMessage({
                id: 'detailPanel.column.productCode',
                defaultMessage: '物料号'
            }),
            dataIndex: 'productCode'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productName',
                defaultMessage: '物料名称'
            }),
            dataIndex: 'productName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.quantity',
                defaultMessage: '数量'
            }),
            dataIndex: 'quantity'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.price',
                defaultMessage: '单价'
            }),
            dataIndex: 'price',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.totalPrice',
                defaultMessage: '总价'
            }),
            dataIndex: 'totalPrice',
            render: text => formatAmount(text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productGroupCode',
                defaultMessage: '物料组编号'
            }),
            dataIndex: 'productGroupCode'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productGroupName',
                defaultMessage: '物料组名称'
            }),
            dataIndex: 'productGroupName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productCategoryCode',
                defaultMessage: '车型编号'
            }),
            dataIndex: 'productCategoryCode'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.productCategoryName',
                defaultMessage: '车型名称'
            }),
            dataIndex: 'productCategoryName'
        },
        //  {
        //     title: formatMessage({
        //         id: 'detailPanel.column.insidePrice',
        //         defaultMessage: '内销价'
        //     }),
        //     dataIndex: 'insidePrice',
        //     render: text => formatAmount(text)
        // }, {
        //     title: formatMessage({
        //         id: 'detailPanel.column.insideTotalPrice',
        //         defaultMessage: '内销总价'
        //     }),
        //     dataIndex: 'insideTotalPrice',
        //     render: text => formatAmount(text)
        // }, 
        {
            title: formatMessage({
                id: 'detailPanel.column.proBatchNumber',
                defaultMessage: '生产批次号'
            }),
            dataIndex: 'proBatchNumber'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.remark',
                defaultMessage: '备注'
            }),
            dataIndex: 'remark'
        }];
        const columnResults = [{
            title: formatMessage({
                id: 'detailPanel.column.approverCode',
                defaultMessage: '审核人编号'
            }),
            dataIndex: 'approverCode'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approverName',
                defaultMessage: '审核人姓名'
            }),
            dataIndex: 'approverName'
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveTime',
                defaultMessage: '审核时间'
            }),
            dataIndex: 'approveTime',
            render: text => formatDateTime(text, DATETIME_FORMAT)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveComment',
                defaultMessage: '审核意见'
            }),
            dataIndex: 'approveComment',
            render: text => <Ellipsis tooltip fullWidthRecognition length={36}>{text}</Ellipsis>
        }, {
            title: formatMessage({
                id: 'detailPanel.column.approveResult',
                defaultMessage: '判定结果'
            }),
            dataIndex: 'approveResult',
            render: text => conventEnumValueToString(saleOrderResultJudgeResult, text)
        }, {
            title: formatMessage({
                id: 'detailPanel.column.nextOperation',
                defaultMessage: '下一步操作'
            }),
            dataIndex: 'nextOperation'
        }];
        if(hasPermissions(this.props.permissions, PERMISSION.update) && hasPermissions(data.options, PERMISSION.update))
            operations.push(<Button key="update" onClick={this.handleUpdateClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.update',
                    defaultMessage: '编辑'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.submit) && hasPermissions(data.options, PERMISSION.submit))
            operations.push(<WrappedPopconfirm
                key="submit"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickSubmitBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.submit',
                    defaultMessage: '是否确认提交？'
                })}>
                <Button key="submit" size="small">{
                    formatMessage({
                        id: 'detailPanel.btn.submit',
                        defaultMessage: '提交'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.approve) && hasPermissions(data.options, PERMISSION.approve))
            operations.push(<Button key="approve" onClick={this.handleApproveClick} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.approve',
                    defaultMessage: '审核'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.abandon) && hasPermissions(data.options, PERMISSION.abandon))
            operations.push(<WrappedPopconfirm
                key="abandon"
                id={this.props.id}
                placement="topLeft"
                onConfirm={this.onClickAbandonBtn}
                title={formatMessage({
                    id: 'detailPanel.validate.abandon',
                    defaultMessage: '是否确认作废？'
                })}>
                <Button key="abandon" size="small">{
                    formatMessage({
                        id: 'detailPanel.btn.abandon',
                        defaultMessage: '作废'
                    })
                }</Button>
            </WrappedPopconfirm>);
        if(hasPermissions(this.props.permissions, PERMISSION.print) && hasPermissions(data.options, PERMISSION.print))
            operations.push(<Button key="print" onClick={this.onPrint} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.print',
                    defaultMessage: '打印EXCEL'
                })
            }</Button>);
        if(hasPermissions(this.props.permissions, PERMISSION.printPdf) && hasPermissions(data.options, PERMISSION.printPdf))
            operations.push(<Button key="printPdf" data-id={this.props.id} data-code={this.props.code} onClick={this.onPrintPdf} size="small">{
                formatMessage({
                    id: 'detailPanel.btn.printPdf',
                    defaultMessage: '打印PDF'
                })
            }</Button>);
        return (
            <div>
                <Spin spinning={this.state.loading}>
                    <Card>
                        <DescriptionList size="large" title={<Row><Col span={12}>{formatMessage({
                            id: 'detailPanel.text.saleConfirmation',
                            defaultMessage: '销售确认书'
                        })}</Col>
                        <Col className={`col-align-right ${styles.detail}`} span={12}>{operations}</Col>
                        </Row>}>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.code',
                                defaultMessage: '销确书号'
                            })}>{data.code}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.brand',
                                defaultMessage: '品牌'
                            })}>{`(${data.brandCode})${data.brandName}`}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.marketDepartmentName',
                                defaultMessage: '大区'
                            })}>{data.marketDepartmentName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.dealerCode',
                                defaultMessage: '总代'
                            })}>{`(${data.dealerCode})${data.dealerName}`}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.country',
                                defaultMessage: '国家'
                            })}>{data.country}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.salesOrderCode',
                                defaultMessage: '销售订单编号'
                            })}>{data.salesOrderCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.orderType',
                                defaultMessage: '订单类型'
                            })}>{conventEnumValueToString(saleOrderType, data.orderType)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.currency',
                                defaultMessage: '币种'
                            })}>{conventEnumValueToString(currency, data.currency)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.tradeMethodName',
                                defaultMessage: '贸易方式'
                            })}>{data.tradeMethodName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.salesOrderPriceTerms',
                                defaultMessage: '价格条款'
                            })}>{conventEnumValueToString(saleOrderPriceTerms, data.salesOrderPriceTerms)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.paymentType',
                                defaultMessage: '付款方式'
                            })}>{conventEnumValueToString(paymentType, data.payment)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.taxRate',
                                defaultMessage: '税率'
                            })}>{formatPercent(data.taxRate)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.letterOfCreditCode',
                                defaultMessage: '信用证号'
                            })}>{data.letterOfCreditCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.lCVersionCode',
                                defaultMessage: '信用证版本号'
                            })}>{data.lcVersionCode}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.saleProformaInvoiceCode',
                                defaultMessage: 'PI形式发票'
                            })}>{data.saleProformaInvoiceCode}</Description>
                            {(data.salesOrderPriceTerms === saleOrderPriceTerms.CIF ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CPT ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CIP ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CFR) && <Description term={formatMessage({
                                id: 'detailPanel.text.shipmentAmount',
                                defaultMessage: '运费'
                            })}><strong>{formatAmount(data.shipmentAmount)}</strong></Description>
                            }
                            {(data.salesOrderPriceTerms === saleOrderPriceTerms.CIF ||
                                    data.salesOrderPriceTerms === saleOrderPriceTerms.CIP) && <Description term={formatMessage({
                                id: 'detailPanel.text.insuranceAmount',
                                defaultMessage: '保费'
                            })}><strong>{formatAmount(data.insuranceAmount)}</strong></Description>
                            }
                            <Description term={formatMessage({
                                id: 'detailPanel.text.orderPrice',
                                defaultMessage: '信用证总额'
                            })}><strong>{formatAmount(data.orderPrice)}</strong></Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.cashInPrice',
                                defaultMessage: '信用证余额'
                            })}><strong>{formatAmount(data.cashInPrice)}</strong></Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.otherAmount',
                                defaultMessage: '其他费用'
                            })}><strong>{formatAmount(data.otherAmount)}</strong></Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.productAmount',
                                defaultMessage: '清单总额'
                            })}><strong>{formatAmount(data.productAmount)}</strong></Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.totalAmount',
                                defaultMessage: '总金额'
                            })}><strong>{formatAmount(data.totalAmount)}</strong></Description>
                            {/* <Description term={formatMessage({
                                id: 'detailPanel.text.insideTotalAmount',
                                defaultMessage: '内销总金额'
                            })}><strong>{formatAmount(data.insideTotalAmount)}</strong></Description> */}
                            <Description term={formatMessage({
                                id: 'detailPanel.text.transportType',
                                defaultMessage: '运输方式'
                            })}>{conventEnumValueToString(saleOrderTransportType, data.transportType)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.packingWay',
                                defaultMessage: '包装方式'
                            })}>{conventEnumValueToString(packingWay, data.packingWay)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.carrierName',
                                defaultMessage: '指定货代'
                            })}>{data.carrierName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.shippingPortName',
                                defaultMessage: '发运港口'
                            })}>{data.shippingPortName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.destinationPort',
                                defaultMessage: '目的港口'
                            })}>{data.destinationPort}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.batchNumber',
                                defaultMessage: '批次号'
                            })}>{data.batchNumber}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.marks',
                                defaultMessage: '标记'
                            })}>{data.marks}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.insurance',
                                defaultMessage: '保险'
                            })}>{data.insurance}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.remark',
                                defaultMessage: '备注'
                            })}>{data.remark}</Description>
                        </DescriptionList>
                        <Divider className={styles.divider}/>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.text.title',
                            defaultMessage: '基础信息'
                        })}>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.createTime',
                                defaultMessage: '创建人'
                            })}>{data.creatorName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.creator',
                                defaultMessage: '创建时间'
                            })}>{formatDateTime(data.createTime, DATETIME_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.modifierName',
                                defaultMessage: '修改人'
                            })}>{data.modifierName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.modifierTime',
                                defaultMessage: '修改时间'
                            })}>{formatDateTime(data.modifierTime, DATETIME_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.submitterName',
                                defaultMessage: '提交人'
                            })}>{data.submitterName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.submitTime',
                                defaultMessage: '提交时间'
                            })}>{formatDateTime(data.submitTime, DATETIME_FORMAT)}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.abandonerName',
                                defaultMessage: '作废人'
                            })}>{data.abandonerName}</Description>
                            <Description term={formatMessage({
                                id: 'detailPanel.text.abandonTime',
                                defaultMessage: '作废时间'
                            })}>{formatDateTime(data.abandonTime, DATETIME_FORMAT)}</Description>
                        </DescriptionList>
                    </Card>
                    <Card>
                        <DescriptionList size="large" title={formatMessage({
                            id: 'detailPanel.table.details',
                            defaultMessage: '清单'
                        })}>
                            <Table
                                className="white-space-nowrap"
                                columns={columns}
                                rowKey="id"
                                pagination={false}
                                dataSource={details}
                                footer={() => (<DescriptionList>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalQuantity',
                                        defaultMessage: '总数量'
                                    })}>{totalQuantity ? totalQuantity : null}
                                    </Description>
                                    <Description term={formatMessage({
                                        id: 'detailPanel.operation.totalAmount',
                                        defaultMessage: '总金额'
                                    })}>{formatAmount(totalAmount ? totalAmount : null)}
                                    </Description>
                                    {/* <Description term={formatMessage({
                                        id: 'detailPanel.operation.insideTotalAmount',
                                        defaultMessage: '内销总金额'
                                    })}>{formatAmount(data.insideTotalAmount ? data.insideTotalAmount : null)}
                                    </Description> */}
                                </DescriptionList>)}
                                {...TABLE} />
                        </DescriptionList>
                    </Card>
                    <Card
                        title={formatMessage({
                            id: 'detailPanel.saleConfirmationResults',
                            defaultMessage: '审核结果清单'
                        })}>
                        <Table
                            className="white-space-nowrap"
                            columns={columnResults}
                            rowKey="id"
                            pagination={false}
                            dataSource={saleConfirmationResults}
                            {...TABLE} />
                    </Card>
                </Spin>
                <div className="page-toolbar">
                    <Button
                        type="primary"
                        disabled={this.state.loading}
                        onClick={this.props.onCancel}>{formatMessage({
                            id: 'detailPanel.text.return',
                            defaultMessage: '返回'
                        })}</Button>
                </div>
            </div>
        );
    }
}

DetailPanel.propTypes = {
    id: PropTypes.string.isRequired,
    permissions: PropTypes.array.isRequired,
    onCancel: PropTypes.func.isRequired,
    history: PropTypes.object,
    intl: PropTypes.object,
    successReturn: PropTypes.func,
};

import {connect} from 'react-redux';
import {
    tableSearch,
    printData,
} from './actions';
import selectorFactory from 'Shared/utils/immutableToJsSelectorFactory';
const getPermissions = selectorFactory(['page', 'domainData', 'permission', 'data']);

const mapStateToProps = (state, props) => ({
    id: props.id,
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    permissions: getPermissions(state),
});
const mapDispatchToProps = (dispatch, props) => ({
    successReturn: () => {
        dispatch(tableSearch());
        props.history.push(routes.query.url());
    },
    onCancel: () => {
        props.history.push(routes.query.url());
    },
    printData: id => dispatch(printData(id)),
});
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(DetailPanel));
